<!-- 结果比对工具组件 -->
<template>
  <div class="comparison-tool">
    <div class="tool-header">
      <h3 class="tool-title">
        <el-icon><DataAnalysis /></el-icon>
        波形比对分析
      </h3>
      <div class="tool-actions">
        <el-button size="small" @click="addComparison" :disabled="selectedResults.length >= 4">
          <el-icon><Plus /></el-icon>
          添加对比
        </el-button>
        <el-button size="small" @click="clearAll">
          <el-icon><Delete /></el-icon>
          清空
        </el-button>
      </div>
    </div>
    
    <div class="comparison-content">
      <!-- 波形对比区域 -->
      <div class="waveform-grid" :class="gridClass">
        <div
          v-for="(result, index) in selectedResults"
          :key="result.id"
          class="waveform-item"
          @click="selectWaveform(index)"
          :class="{ active: activeWaveform === index }"
        >
          <div class="waveform-header">
            <div class="waveform-info">
              <span class="waveform-name">{{ result.name }}</span>
              <span class="waveform-freq">{{ result.frequency }}</span>
            </div>
            <el-button
              size="small"
              text
              @click.stop="removeWaveform(index)"
              class="remove-btn"
            >
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
          
          <!-- 波形图表 -->
          <div class="waveform-chart" :ref="el => chartRefs[index] = el"></div>
          
          <!-- 波形统计信息 -->
          <div class="waveform-stats">
            <div class="stat-row">
              <span>相似度:</span>
              <span class="stat-value similarity" :style="{ color: getSimilarityColor(result.similarity) }">
                {{ result.similarity }}%
              </span>
            </div>
            <div class="stat-row">
              <span>信噪比:</span>
              <span class="stat-value">{{ result.snr }}dB</span>
            </div>
            <div class="stat-row">
              <span>带宽:</span>
              <span class="stat-value">{{ result.bandwidth }}</span>
            </div>
          </div>
        </div>
        
        <!-- 添加新比对的占位符 -->
        <div
          v-if="selectedResults.length < 4"
          class="waveform-placeholder"
          @click="addComparison"
        >
          <el-icon class="placeholder-icon"><Plus /></el-icon>
          <span class="placeholder-text">点击添加波形</span>
        </div>
      </div>
      
      <!-- 详细对比分析 -->
      <div v-if="selectedResults.length >= 2" class="analysis-panel">
        <div class="analysis-header">
          <h4>相关性分析</h4>
          <el-switch
            v-model="showDetailedAnalysis"
            active-text="详细"
            inactive-text="简要"
          />
        </div>
        
        <div class="correlation-matrix" v-if="showDetailedAnalysis">
          <div class="matrix-header">
            <div class="matrix-cell header-cell"></div>
            <div
              v-for="(result, index) in selectedResults"
              :key="`header-${index}`"
              class="matrix-cell header-cell"
            >
              {{ result.name.substring(0, 8) }}...
            </div>
          </div>
          <div
            v-for="(rowResult, rowIndex) in selectedResults"
            :key="`row-${rowIndex}`"
            class="matrix-row"
          >
            <div class="matrix-cell row-header">
              {{ rowResult.name.substring(0, 8) }}...
            </div>
            <div
              v-for="(colResult, colIndex) in selectedResults"
              :key="`cell-${rowIndex}-${colIndex}`"
              class="matrix-cell correlation-cell"
              :style="{ backgroundColor: getCorrelationColor(getCorrelation(rowIndex, colIndex)) }"
            >
              {{ getCorrelation(rowIndex, colIndex) }}%
            </div>
          </div>
        </div>
        
        <!-- 快速对比结果 -->
        <div v-else class="quick-comparison">
          <div class="comparison-summary">
            <div class="summary-item">
              <span class="summary-label">最高相似度:</span>
              <span class="summary-value">{{ maxSimilarity }}%</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">平均相似度:</span>
              <span class="summary-value">{{ avgSimilarity }}%</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">建议操作:</span>
              <span class="summary-value">{{ recommendation }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { DataAnalysis, Plus, Delete, Close } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// Props
const props = defineProps({
  availableResults: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['selectionChange', 'comparisonUpdate'])

// 响应式数据
const selectedResults = ref([])
const activeWaveform = ref(0)
const showDetailedAnalysis = ref(false)
const chartRefs = ref([])

// 计算属性
const gridClass = computed(() => {
  const count = selectedResults.value.length + (selectedResults.value.length < 4 ? 1 : 0)
  if (count <= 2) return 'grid-1x2'
  return 'grid-2x2'
})

const maxSimilarity = computed(() => {
  if (selectedResults.value.length === 0) return 0
  return Math.max(...selectedResults.value.map(r => r.similarity))
})

const avgSimilarity = computed(() => {
  if (selectedResults.value.length === 0) return 0
  const sum = selectedResults.value.reduce((acc, r) => acc + r.similarity, 0)
  return Math.round(sum / selectedResults.value.length)
})

const recommendation = computed(() => {
  const avg = avgSimilarity.value
  if (avg >= 80) return '高度相似，建议深度分析'
  if (avg >= 60) return '中等相似，可进一步比对'
  return '相似度较低，建议调整参数'
})

// 方法
const addComparison = () => {
  if (selectedResults.value.length >= 4) return
  
  // 模拟添加一个波形结果
  const newResult = {
    id: Date.now(),
    name: `信号_${selectedResults.value.length + 1}`,
    frequency: `${(2.4 + Math.random() * 2.6).toFixed(1)}GHz`,
    similarity: Math.round(60 + Math.random() * 35),
    snr: Math.round(15 + Math.random() * 25),
    bandwidth: `${(10 + Math.random() * 90).toFixed(1)}MHz`,
    waveformData: generateWaveformData()
  }
  
  selectedResults.value.push(newResult)
  
  nextTick(() => {
    renderChart(selectedResults.value.length - 1)
  })
  
  emit('selectionChange', selectedResults.value)
}

const removeWaveform = (index) => {
  selectedResults.value.splice(index, 1)
  if (activeWaveform.value >= selectedResults.value.length) {
    activeWaveform.value = Math.max(0, selectedResults.value.length - 1)
  }
  
  nextTick(() => {
    renderAllCharts()
  })
  
  emit('selectionChange', selectedResults.value)
}

const clearAll = () => {
  selectedResults.value = []
  activeWaveform.value = 0
  emit('selectionChange', selectedResults.value)
}

const selectWaveform = (index) => {
  activeWaveform.value = index
}

const getSimilarityColor = (similarity) => {
  if (similarity >= 80) return '#10b981'
  if (similarity >= 60) return '#f59e0b'
  return '#ef4444'
}

const getCorrelation = (row, col) => {
  if (row === col) return 100
  // 模拟相关性计算
  const base = Math.abs(selectedResults.value[row].similarity - selectedResults.value[col].similarity)
  return Math.max(10, Math.round(90 - base))
}

const getCorrelationColor = (correlation) => {
  const intensity = correlation / 100
  return `rgba(59, 130, 246, ${intensity * 0.8 + 0.2})`
}

const generateWaveformData = () => {
  const data = []
  for (let i = 0; i < 100; i++) {
    const x = i / 10
    const y = Math.sin(x) + Math.sin(x * 3) * 0.3 + (Math.random() - 0.5) * 0.2
    data.push([x, y])
  }
  return data
}

const renderChart = (index) => {
  const chartEl = chartRefs.value[index]
  if (!chartEl) return
  
  const chart = echarts.init(chartEl, 'dark')
  const result = selectedResults.value[index]
  
  const option = {
    grid: {
      left: '5%',
      right: '5%',
      top: '5%',
      bottom: '5%'
    },
    xAxis: {
      type: 'value',
      show: false
    },
    yAxis: {
      type: 'value',
      show: false
    },
    series: [{
      type: 'line',
      data: result.waveformData,
      smooth: true,
      symbol: 'none',
      lineStyle: {
        color: '#3b82f6',
        width: 2
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(59, 130, 246, 0.4)'
          }, {
            offset: 1,
            color: 'rgba(59, 130, 246, 0.1)'
          }]
        }
      }
    }]
  }
  
  chart.setOption(option)
  
  // 响应式调整
  const resizeObserver = new ResizeObserver(() => {
    chart.resize()
  })
  resizeObserver.observe(chartEl)
}

const renderAllCharts = () => {
  nextTick(() => {
    selectedResults.value.forEach((_, index) => {
      renderChart(index)
    })
  })
}

// 生命周期
onMounted(() => {
  // 初始化一些示例数据
  addComparison()
  addComparison()
})

// 监听数据变化
watch(selectedResults, () => {
  emit('comparisonUpdate', {
    count: selectedResults.value.length,
    maxSimilarity: maxSimilarity.value,
    avgSimilarity: avgSimilarity.value
  })
}, { deep: true })
</script>

<style scoped>
.comparison-tool {
  background: #263445; /* 使用与主题一致的深色背景 */
  border-radius: 1vh;
  padding: 2vh;
  border: 1px solid #2d3a4b; /* 深色边框 */
  box-shadow: 0 0.5vh 2vh rgba(0, 0, 0, 0.3);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tool-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2vh;
}

.tool-title {
  display: flex;
  align-items: center;
  gap: 1vh;
  font-size: 1.6vh;
  font-weight: 600;
  color: #e2e8f0;
  margin: 0;
}

.tool-actions {
  display: flex;
  gap: 1vh;
}

.comparison-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2vh;
  overflow: hidden;
}

.waveform-grid {
  display: grid;
  gap: 1.5vh;
  flex: 1;
  min-height: 0;
}

.grid-1x2 {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr;
}

.grid-2x2 {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
}

.waveform-item {
  background: #1f2d3d; /* 使用深色背景 */
  border-radius: 1vh;
  border: 2px solid #2d3a4b; /* 深色边框 */
  padding: 1vh;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.waveform-item:hover,
.waveform-item.active {
  border-color: #3b82f6;
  box-shadow: 0 0 1vh rgba(59, 130, 246, 0.3);
}

.waveform-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1vh;
}

.waveform-info {
  display: flex;
  flex-direction: column;
  gap: 0.2vh;
}

.waveform-name {
  font-size: 1.3vh;
  font-weight: 600;
  color: #e2e8f0;
}

.waveform-freq {
  font-size: 1.1vh;
  color: #94a3b8;
}

.remove-btn {
  color: #ef4444;
  padding: 0.5vh;
}

.waveform-chart {
  flex: 1;
  min-height: 8vh;
  background: rgba(51, 65, 85, 0.3);
  border-radius: 0.5vh;
  margin-bottom: 1vh;
}

.waveform-stats {
  display: flex;
  flex-direction: column;
  gap: 0.5vh;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  font-size: 1.1vh;
  color: #cbd5e1;
}

.stat-value {
  font-weight: 600;
  color: #3b82f6;
}

.stat-value.similarity {
  font-weight: 700;
}

.waveform-placeholder {
  background: rgba(31, 45, 61, 0.3); /* 使用深色背景 */
  border: 2px dashed #2d3a4b; /* 深色边框 */
  border-radius: 1vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1vh;
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 15vh;
}

.waveform-placeholder:hover {
  border-color: #3b82f6;
  background: rgba(59, 130, 246, 0.1);
}

.placeholder-icon {
  font-size: 3vh;
  color: #64748b;
}

.placeholder-text {
  font-size: 1.2vh;
  color: #64748b;
}

.analysis-panel {
  background: #1f2d3d; /* 使用深色背景 */
  border-radius: 1vh;
  padding: 1.5vh;
  border: 1px solid #2d3a4b; /* 深色边框 */
  max-height: 25vh;
  overflow-y: auto;
}

.analysis-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5vh;
}

.analysis-header h4 {
  margin: 0;
  font-size: 1.4vh;
  color: #e2e8f0;
}

.correlation-matrix {
  display: grid;
  gap: 0.2vh;
  font-size: 1.1vh;
}

.matrix-header,
.matrix-row {
  display: grid;
  grid-template-columns: repeat(var(--cols), 1fr);
  gap: 0.2vh;
}

.matrix-cell {
  padding: 0.8vh;
  text-align: center;
  border-radius: 0.3vh;
  background: rgba(51, 65, 85, 0.4);
  color: #cbd5e1;
}

.header-cell,
.row-header {
  background: rgba(71, 85, 105, 0.6);
  font-weight: 600;
  color: #e2e8f0;
}

.correlation-cell {
  font-weight: 600;
  color: #ffffff;
}

.quick-comparison {
  display: flex;
  flex-direction: column;
  gap: 1vh;
}

.comparison-summary {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1vh;
}

.summary-item {
  background: rgba(51, 65, 85, 0.4);
  padding: 1vh;
  border-radius: 0.5vh;
  text-align: center;
}

.summary-label {
  display: block;
  font-size: 1.1vh;
  color: #94a3b8;
  margin-bottom: 0.5vh;
}

.summary-value {
  display: block;
  font-size: 1.3vh;
  font-weight: 600;
  color: #3b82f6;
}
</style>